﻿using LineFocus.Nikcron.Common;
using LineFocus.Nikcron.Models;
using Nickron.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LineFocus.Nikcron.Controllers
{
    public class RetailerController : BaseController
    {
        //
        // GET: /Retailer/

        public ActionResult Index()
        {
            ViewBag.Header = "Retailer";
            ViewBag.Caption = "Listing";
            return View();
        }

        [HttpGet]
        public JsonResult GetRetailers()
        {
            ApplicationDBContext db = new ApplicationDBContext();
            var companies = from c in db.Offices.OfType<Company>().ToList()
                            join s in db.Offices.OfType<Stockhouse>().ToList() on c.Id equals s.CompanyId
                            join d in db.Offices.OfType<Distributor>().ToList() on s.Id equals d.StockhouseId
                            join de in db.Offices.OfType<Dealers>().ToList() on d.Id equals de.DistributorId
                            join r in db.Offices.OfType<Retailer>().ToList().Where(r => r.Status.IsDeleted != true) on de.Id equals r.DealersId
                            select new
                            {
                                CompanyId = c.Id,
                                CompanyName = c.Name,
                                StockhouseId = s.Id,
                                StockhouseName = s.Name,
                                DistributorId = de.Id,
                                DistributorName = de.Name,
                                DealerId = de.Id,
                                DealerName = de.Name,
                                Id = r.Id,
                                Name = r.Name,
                                ContactPerson = r.ContactPerson,
                                AddressLine1 = r.Address.Address1,
                                AddressLine2 = r.Address.Address2,
                                AddressCity = r.Address.City,
                                AddressState = r.Address.State,
                                AddressZip = r.Address.Zip,
                                Mobile = string.Join(" ", r.Contact1.Mobile, r.Contact2.Mobile),
                                Phone = string.Join(" ", r.Contact1.Phone, r.Contact2.Mobile),
                                Email = string.Join(" ", r.Contact1.Email, r.Contact2.Email),
                                Web = string.Join(" ", r.Contact1.Website, r.Contact2.Website)
                            };
            JsonResult result = new JsonResult();
            result.Data = companies;
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
        }

        [HttpGet]
        public ActionResult Maintenance(Int32? Id)
        {
            Lookup Lookup_Companies = new Lookup();
            Lookup Lookup_States = new Lookup();
            Lookup Lookup_Countries = new Lookup();
            Lookup Lookup_Stockhouses = new Lookup();
            Lookup Lookup_Distributors = new Lookup();  
            Lookup Lookup_Dealers = new Lookup();

            ApplicationDBContext db = new ApplicationDBContext();

            var query1 = from records in db.States.OfType<State>().ToList().Where(s => s.Status.IsDeleted != true)
                         select new LookupItem() { Id = records.Id, Name = records.Name };
            Lookup_States.Items = query1.ToList();

            var query2 = from records in db.Countries.OfType<Country>().ToList().Where(c => c.Status.IsDeleted != true)
                         select new LookupItem() { Id = records.Id, Name = records.Name };
            Lookup_Countries.Items = query2.ToList();

            var query4 = from records in db.Offices.OfType<Company>().ToList().Where(c => c.Status.IsDeleted != true)
                         select new LookupItem() { Id = records.Id, Name = records.Name };
            Lookup_Companies.Items = query4.ToList();

            var query5 = from records in db.Offices.OfType<Stockhouse>().ToList().Where(s => s.Status.IsDeleted != true)
                         select new LookupItem() { Id = records.Id, Name = records.Name, ParentId = records.CompanyId };
            Lookup_Stockhouses.Parent = "Company";
            Lookup_Stockhouses.Items = query5.ToList();

            var query6 = from records in db.Offices.OfType<Distributor>().ToList().Where(d => d.Status.IsDeleted != true)
                         select new LookupItem() { Id = records.Id, Name = records.Name, ParentId = records.StockhouseId };
            Lookup_Distributors.Parent = "Stockhouse";
            Lookup_Distributors.Items = query6.ToList();

            var query7 = from records in db.Offices.OfType<Dealers>().ToList().Where(de => de.Status.IsDeleted != true)
                         select new LookupItem() { Id = records.Id, Name = records.Name, ParentId = records.DistributorId };
            Lookup_Dealers.Parent = "Distributor";
            Lookup_Dealers.Items = query7.ToList();

            ViewBag.Header = "Retailer";         
            ViewBag.States = Lookup_States;
            ViewBag.Countries = Lookup_Countries;
            ViewBag.Companies = Lookup_Companies;
            ViewBag.Stockhouses = Lookup_Stockhouses;
            ViewBag.Distributors = Lookup_Distributors;
            ViewBag.Dealers = Lookup_Dealers;

            if (Id.HasValue)
            {
                ViewBag.Id = Id;
                ViewBag.Caption = "Edit";
                Retailer Retailer = db.Offices.OfType<Retailer>().Where(d => d.Id == Id).FirstOrDefault();
                Retailer.Dealer = db.Offices.OfType<Dealers>().Where(d => d.Id == Retailer.DealersId).FirstOrDefault();
                Retailer.Dealer.Distributor = db.Offices.OfType<Distributor>().Where(d => d.Id == Retailer.Dealer.DistributorId).FirstOrDefault();
                Retailer.Dealer.Distributor.Stockhouse = db.Offices.OfType<Stockhouse>().Where(d => d.Id == Retailer.Dealer.Distributor.StockhouseId).FirstOrDefault();
                Retailer.Dealer.Distributor.Stockhouse.Company = db.Offices.OfType<Company>().Where(d => d.Id == Retailer.Dealer.Distributor.Stockhouse.CompanyId).FirstOrDefault();
                return View(Retailer);
            }
            else
            {
                Retailer Retailer = new Retailer();
                Retailer.Dealer = new Dealers();
                Retailer.Dealer.Distributor = new Distributor();
                Retailer.Dealer.Distributor.Stockhouse = new Stockhouse();
                Retailer.Dealer.Distributor.Stockhouse.Company = new Company();
                ViewBag.Caption = "New";
                return View(Retailer);
            }

        }

        public ActionResult Maintenance(FormCollection formCollection)
        {
            ApplicationDBContext db = new ApplicationDBContext();
            Retailer Retailer;
            User User = new Nickron.Database.User();
            Int32 RetailerId = 0;
            Int32.TryParse(formCollection["Id"], out RetailerId);
            if (RetailerId == 0)
            {
                Retailer = new Retailer();
                Retailer.DealersId = Int32.Parse(formCollection["Dealer"]);
            }
            else
                Retailer = db.Offices.OfType<Retailer>().Where(s => s.Id == RetailerId).FirstOrDefault();

            Retailer.Location = formCollection["Location"];
            Retailer.Name = formCollection["Retailer"];
            Retailer.ContactPerson = formCollection["ContactPerson"];
            if (!string.IsNullOrEmpty(formCollection["Joindate"]))
                Retailer.JoiningDate = DateTime.Parse(formCollection["Joindate"]);
            Retailer.FirmRegistration = formCollection["NameOfthefirm"];
            Retailer.Address.Address1 = formCollection["Address1"];
            Retailer.Address.Address2 = formCollection["Address2"];
            Retailer.Address.City = formCollection["City"];
            Retailer.Address.Zip = formCollection["Zip"];
            Retailer.Address.State = formCollection["State"];
            Retailer.Address.Country = formCollection["Country"];
            Retailer.Contact1.Mobile = formCollection["Mobile1"];
            Retailer.Contact2.Mobile = formCollection["Mobile2"];
            Retailer.Contact1.Phone = formCollection["Phone"];
            Retailer.Contact1.Email = formCollection["Email1"];
            Retailer.Contact2.Email = formCollection["Email2"];
            Retailer.Contact1.Website = formCollection["Web"];
            Retailer.PAN = formCollection["Panno"];
            Retailer.TIN = formCollection["Tinno"];
            Retailer.CST = formCollection["CSTno"];
            Retailer.IDProof = formCollection["Idproff"];
            Retailer.BusinessPresentAddress = formCollection["CommunicationAddress"];
            Retailer.CurrentBusiness = formCollection["CurrentBusiness"];
            Retailer.BankName = formCollection["NameOfBank"];
            Retailer.BankAccountNumber = formCollection["BankAcNo"];
            Retailer.BankIFSC = formCollection["IFSCCode"];
            Retailer.Coverages = formCollection["BusinesscoveredArea"];
            if (!(string.IsNullOrEmpty(formCollection["ManPower"])))
                Retailer.StrengthOfFieldForce = Int32.Parse(formCollection["ManPower"]);
            if (!(string.IsNullOrEmpty(formCollection["PeakSalesPeriod1"]) && string.IsNullOrEmpty(formCollection["PeakSalesPeriod2"])))
                Retailer.PeakSalesPeriod = DateTime.Parse(formCollection["PeakSalesPeriod1"]).ToShortDateString() + " To " + DateTime.Parse(formCollection["PeakSalesPeriod2"]).ToShortDateString();
            //upload
            string Pdfupload = string.Empty;
            if (Request.Files["Pdfupload"] != null && Request.Files["Pdfupload"].ContentLength > 0)
            {
                HttpPostedFileBase hpf = Request.Files["Pdfupload"] as HttpPostedFileBase;
                Pdfupload = Randomizer.GetString(10) + ".pdf";
                hpf.SaveAs(Server.MapPath("~/Uploads/" + Pdfupload));
                Retailer.UploadedFile = Pdfupload;
            }
            Retailer.PopularFestivalFairs = formCollection["Popularfestivals"];
            Retailer.RecommendationFrom = formCollection["Recommendedby"];
            Retailer.Comments = formCollection["Comments"];
            if (RetailerId == 0)
                db.Offices.AddObject(Retailer);
            db.SaveChanges();

            if (RetailerId == 0)
            {
                AddNewUser(Retailer, OfficeTypes.Retailer);
            }
            return RedirectToAction("Index");
        }

        public ActionResult Delete(Int32? Id)
        {
            if (Id.HasValue)
            {
                ApplicationDBContext db = new ApplicationDBContext();
                Retailer Retailer = db.Offices.OfType<Retailer>().Where(c => c.Id == Id).FirstOrDefault();
                db.DeleteObject(Retailer);
                db.SaveChanges();
            }
            TempData["AlertMessage"] = "Data has been deleted successfully";
            return RedirectToAction("Index");
        }

    }
}
